﻿using System;
using System.Collections.Generic;
using Gp.Examples.FullCalendar.Core;
using Gp.Examples.FullCalendar.Core.Repository;
using Gp.Examples.FullCalendar.Infrastructure;
using NHibernate;

namespace Gp.Examples.FullCalendar.Data.NHibernate.Repository
{
    public class EventRepository : IEventRepository
    {
        private ISession Session { get; set; }

        public EventRepository(IMapper mapper)
        {
            Session = mapper.CurrentSession as ISession;
        }

        public void Delete(Event evt)
        {            
            Session.Delete(evt);
            Session.Flush();
        }

        public Event GetEventById(int eventId)
        {
            return Session.Get<Event>(eventId);
        }

        public IList<Event> ListEventsForUser(string userName, DateTime fromDate, DateTime toDate)
        {
            var queryString = "from Event e where e.User.UserName=? and e.FromDate>=? and e.ToDate<?";
            var query = Session.CreateQuery(queryString);
            query.SetParameter(0, userName);
            query.SetParameter(1, fromDate.Date);
            query.SetParameter(2, toDate.Date.AddDays(1));
            return query.List<Event>();
        }

        public void Save(Event instance)
        {
            Session.SaveOrUpdate(instance);
        }
    }
}
